package com.thread.xxstudy;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 有返回值的线程
 * 等所有线程都执行完以后  所有返回值相加打印
 */
public class JoinWaitFuture {

    AtomicInteger a = new AtomicInteger(0);

    class Wait implements Callable {
        @Override
        public Integer call() {

            int s = a.incrementAndGet();
            System.out.println(s);
            return s;
        }
    }


    void join() {
        List<Thread> list = new ArrayList<>();
        List<FutureTask<Integer>> future = new ArrayList<>();
        Wait wait = new Wait();

        for (int i = 0; i < 10; i++) {
            FutureTask<Integer> task = new FutureTask<Integer>(wait);
            Thread thread = new Thread(task);
            list.add(thread);
            future.add(task);
            thread.start();
        }





        /**
         * lambda使用变量必须为final修饰
         */
//        final int sum ;
//      future.forEach(futures-> {
//          try {
//              int lim = futures.get();
//              sum = sum + lim;
//          } catch (InterruptedException e) {
//              e.printStackTrace();
//          } catch (ExecutionException e) {
//              e.printStackTrace();
//          }
//      } );
        int sum = 0;
        for (FutureTask<Integer> futureTask : future) {
            try {
                //get方法为阻塞方法 如果线程没有执行完会一直阻塞到线程执行完
                Integer integer = futureTask.get();
                sum = sum + integer;
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        System.out.println("sum=" + sum);


    }

 /*   public static void main(String[] args) {
        new JoinWaitFuture().join();
    }*/
}
